<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="180px"
      v-loading="formLoading"
    >
      <el-form-item label="订单编号" prop="orderId">
        <el-input v-model="formData.orderId" placeholder="请输入订单编号" />
      </el-form-item>
      <el-form-item label="订单号" prop="orderNo">
        <el-input v-model="formData.orderNo" placeholder="请输入订单号" />
      </el-form-item>
      <el-form-item label="行号" prop="lineNo">
        <el-input v-model="formData.lineNo" placeholder="请输入行号" />
      </el-form-item>
      <el-form-item label="SPU编号" prop="spuId">
        <el-input v-model="formData.spuId" placeholder="请输入SPU编号" />
      </el-form-item>
      <el-form-item label="SKU编号" prop="skuId">
        <el-input v-model="formData.skuId" placeholder="请输入SKU编号" />
      </el-form-item>
      <el-form-item label="SKU编码" prop="skuCode">
        <el-input v-model="formData.skuCode" placeholder="请输入SKU编码" />
      </el-form-item>
      <el-form-item label="商品名称" prop="productName">
        <el-input v-model="formData.productName" placeholder="请输入商品名称" />
      </el-form-item>
      <el-form-item label="英文商品名称" prop="productNameEn">
        <el-input v-model="formData.productNameEn" placeholder="请输入英文商品名称" />
      </el-form-item>
      <el-form-item label="商品图片" prop="productImage">
        <UploadImg v-model="formData.productImage" />
      </el-form-item>
      <el-form-item label="品牌名称" prop="brandName">
        <el-input v-model="formData.brandName" placeholder="请输入品牌名称" />
      </el-form-item>
      <el-form-item label="分类名称" prop="categoryName">
        <el-input v-model="formData.categoryName" placeholder="请输入分类名称" />
      </el-form-item>
      <el-form-item label="规格值JSON" prop="specValues">
        <el-input v-model="formData.specValues" placeholder="请输入规格值JSON" />
      </el-form-item>
      <el-form-item label="条形码" prop="barcode">
        <el-input v-model="formData.barcode" placeholder="请输入条形码" />
      </el-form-item>
      <el-form-item label="UPC码" prop="upcCode">
        <el-input v-model="formData.upcCode" placeholder="请输入UPC码" />
      </el-form-item>
      <el-form-item label="HS编码" prop="hsCode">
        <el-input v-model="formData.hsCode" placeholder="请输入HS编码" />
      </el-form-item>
      <el-form-item label="原产国代码" prop="originCountry">
        <el-input v-model="formData.originCountry" placeholder="请输入原产国代码" />
      </el-form-item>
      <el-form-item label="购买数量" prop="quantity">
        <el-input v-model="formData.quantity" placeholder="请输入购买数量" />
      </el-form-item>
      <el-form-item label="单价" prop="unitPrice">
        <el-input v-model="formData.unitPrice" placeholder="请输入单价" />
      </el-form-item>
      <el-form-item label="总价" prop="totalPrice">
        <el-input v-model="formData.totalPrice" placeholder="请输入总价" />
      </el-form-item>
      <el-form-item label="货币代码" prop="currencyCode">
        <el-input v-model="formData.currencyCode" placeholder="请输入货币代码" />
      </el-form-item>
      <el-form-item label="折扣金额" prop="discountAmount">
        <el-input v-model="formData.discountAmount" placeholder="请输入折扣金额" />
      </el-form-item>
      <el-form-item label="优惠券金额" prop="couponAmount">
        <el-input v-model="formData.couponAmount" placeholder="请输入优惠券金额" />
      </el-form-item>
      <el-form-item label="最终价格" prop="finalPrice">
        <el-input v-model="formData.finalPrice" placeholder="请输入最终价格" />
      </el-form-item>
      <el-form-item label="重量（kg）" prop="weight">
        <el-input v-model="formData.weight" placeholder="请输入重量（kg）" />
      </el-form-item>
      <el-form-item label="长度（cm）" prop="length">
        <el-input v-model="formData.length" placeholder="请输入长度（cm）" />
      </el-form-item>
      <el-form-item label="宽度（cm）" prop="width">
        <el-input v-model="formData.width" placeholder="请输入宽度（cm）" />
      </el-form-item>
      <el-form-item label="高度（cm）" prop="height">
        <el-input v-model="formData.height" placeholder="请输入高度（cm）" />
      </el-form-item>
      <el-form-item label="体积（立方米）" prop="volume">
        <el-input v-model="formData.volume" placeholder="请输入体积（立方米）" />
      </el-form-item>
      <el-form-item label="成本价" prop="costPrice">
        <el-input v-model="formData.costPrice" placeholder="请输入成本价" />
      </el-form-item>
      <el-form-item label="利润金额" prop="profitAmount">
        <el-input v-model="formData.profitAmount" placeholder="请输入利润金额" />
      </el-form-item>
      <el-form-item label="利润率" prop="profitRate">
        <el-input v-model="formData.profitRate" placeholder="请输入利润率" />
      </el-form-item>
      <el-form-item label="税率" prop="taxRate">
        <el-input v-model="formData.taxRate" placeholder="请输入税率" />
      </el-form-item>
      <el-form-item label="税费" prop="taxAmount">
        <el-input v-model="formData.taxAmount" placeholder="请输入税费" />
      </el-form-item>
      <el-form-item label="保修期（天）" prop="warrantyPeriod">
        <el-input v-model="formData.warrantyPeriod" placeholder="请输入保修期（天）" />
      </el-form-item>
      <el-form-item label="是否礼品" prop="isGift">
        <el-radio-group v-model="formData.isGift">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="礼品留言" prop="giftMessage">
        <el-input v-model="formData.giftMessage" placeholder="请输入礼品留言" />
      </el-form-item>
      <el-form-item label="是否定制商品" prop="isCustomized">
        <el-radio-group v-model="formData.isCustomized">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="定制信息JSON" prop="customizationInfo">
        <el-input v-model="formData.customizationInfo" placeholder="请输入定制信息JSON" />
      </el-form-item>
      <el-form-item label="发货截止时间" prop="deliveryDeadline">
        <el-date-picker
          v-model="formData.deliveryDeadline"
          type="date"
          value-format="x"
          placeholder="选择发货截止时间"
        />
      </el-form-item>
      <el-form-item label="预计送达日期" prop="expectedDeliveryDate">
        <el-date-picker
          v-model="formData.expectedDeliveryDate"
          type="date"
          value-format="x"
          placeholder="选择预计送达日期"
        />
      </el-form-item>
      <el-form-item label="履约状态" prop="fulfillmentStatus">
        <el-radio-group v-model="formData.fulfillmentStatus">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_FULFILLMENT_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="分配仓库编号" prop="allocatedWarehouseId">
        <el-input v-model="formData.allocatedWarehouseId" placeholder="请输入分配仓库编号" />
      </el-form-item>
      <el-form-item label="已分配数量" prop="allocatedQuantity">
        <el-input v-model="formData.allocatedQuantity" placeholder="请输入已分配数量" />
      </el-form-item>
      <el-form-item label="已拣货数量" prop="pickedQuantity">
        <el-input v-model="formData.pickedQuantity" placeholder="请输入已拣货数量" />
      </el-form-item>
      <el-form-item label="已发货数量" prop="shippedQuantity">
        <el-input v-model="formData.shippedQuantity" placeholder="请输入已发货数量" />
      </el-form-item>
      <el-form-item label="已送达数量" prop="deliveredQuantity">
        <el-input v-model="formData.deliveredQuantity" placeholder="请输入已送达数量" />
      </el-form-item>
      <el-form-item label="已退货数量" prop="returnedQuantity">
        <el-input v-model="formData.returnedQuantity" placeholder="请输入已退货数量" />
      </el-form-item>
      <el-form-item label="已退款数量" prop="refundedQuantity">
        <el-input v-model="formData.refundedQuantity" placeholder="请输入已退款数量" />
      </el-form-item>
      <el-form-item label="取消原因" prop="cancelReason">
        <el-input v-model="formData.cancelReason" placeholder="请输入取消原因" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { OrderItemApi, OrderItemVO } from '@/api/crossborder/orderitem'
import { DICT_TYPE, getIntDictOptions, getBoolDictOptions } from '@/utils/dict'

/** 跨境电商订单明细 表单 */
defineOptions({ name: 'OrderItemForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  orderId: undefined,
  orderNo: undefined,
  lineNo: undefined,
  spuId: undefined,
  skuId: undefined,
  skuCode: undefined,
  productName: undefined,
  productNameEn: undefined,
  productImage: undefined,
  brandName: undefined,
  categoryName: undefined,
  specValues: undefined,
  barcode: undefined,
  upcCode: undefined,
  hsCode: undefined,
  originCountry: undefined,
  quantity: undefined,
  unitPrice: undefined,
  totalPrice: undefined,
  currencyCode: undefined,
  discountAmount: undefined,
  couponAmount: undefined,
  finalPrice: undefined,
  weight: undefined,
  length: undefined,
  width: undefined,
  height: undefined,
  volume: undefined,
  costPrice: undefined,
  profitAmount: undefined,
  profitRate: undefined,
  taxRate: undefined,
  taxAmount: undefined,
  warrantyPeriod: undefined,
  isGift: undefined,
  giftMessage: undefined,
  isCustomized: undefined,
  customizationInfo: undefined,
  deliveryDeadline: undefined,
  expectedDeliveryDate: undefined,
  fulfillmentStatus: undefined,
  allocatedWarehouseId: undefined,
  allocatedQuantity: undefined,
  pickedQuantity: undefined,
  shippedQuantity: undefined,
  deliveredQuantity: undefined,
  returnedQuantity: undefined,
  refundedQuantity: undefined,
  cancelReason: undefined,
  remark: undefined,
})
const formRules = reactive({
  orderId: [{ required: true, message: '订单编号不能为空', trigger: 'blur' }],
  orderNo: [{ required: true, message: '订单号不能为空', trigger: 'blur' }],
  lineNo: [{ required: true, message: '行号不能为空', trigger: 'blur' }],
  spuId: [{ required: true, message: 'SPU编号不能为空', trigger: 'blur' }],
  skuId: [{ required: true, message: 'SKU编号不能为空', trigger: 'blur' }],
  skuCode: [{ required: true, message: 'SKU编码不能为空', trigger: 'blur' }],
  productName: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
  quantity: [{ required: true, message: '购买数量不能为空', trigger: 'blur' }],
  unitPrice: [{ required: true, message: '单价不能为空', trigger: 'blur' }],
  totalPrice: [{ required: true, message: '总价不能为空', trigger: 'blur' }],
  currencyCode: [{ required: true, message: '货币代码不能为空', trigger: 'blur' }],
  discountAmount: [{ required: true, message: '折扣金额不能为空', trigger: 'blur' }],
  couponAmount: [{ required: true, message: '优惠券金额不能为空', trigger: 'blur' }],
  finalPrice: [{ required: true, message: '最终价格不能为空', trigger: 'blur' }],
  isGift: [{ required: true, message: '是否礼品不能为空', trigger: 'blur' }],
  isCustomized: [{ required: true, message: '是否定制商品不能为空', trigger: 'blur' }],
  fulfillmentStatus: [{ required: true, message: '履约状态不能为空', trigger: 'blur' }],
  allocatedQuantity: [{ required: true, message: '已分配数量不能为空', trigger: 'blur' }],
  pickedQuantity: [{ required: true, message: '已拣货数量不能为空', trigger: 'blur' }],
  shippedQuantity: [{ required: true, message: '已发货数量不能为空', trigger: 'blur' }],
  deliveredQuantity: [{ required: true, message: '已送达数量不能为空', trigger: 'blur' }],
  returnedQuantity: [{ required: true, message: '已退货数量不能为空', trigger: 'blur' }],
  refundedQuantity: [{ required: true, message: '已退款数量不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await OrderItemApi.getOrderItem(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OrderItemVO
    if (formType.value === 'create') {
      await OrderItemApi.createOrderItem(data)
      message.success(t('common.createSuccess'))
    } else {
      await OrderItemApi.updateOrderItem(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    orderId: undefined,
    orderNo: undefined,
    lineNo: undefined,
    spuId: undefined,
    skuId: undefined,
    skuCode: undefined,
    productName: undefined,
    productNameEn: undefined,
    productImage: undefined,
    brandName: undefined,
    categoryName: undefined,
    specValues: undefined,
    barcode: undefined,
    upcCode: undefined,
    hsCode: undefined,
    originCountry: undefined,
    quantity: undefined,
    unitPrice: undefined,
    totalPrice: undefined,
    currencyCode: undefined,
    discountAmount: undefined,
    couponAmount: undefined,
    finalPrice: undefined,
    weight: undefined,
    length: undefined,
    width: undefined,
    height: undefined,
    volume: undefined,
    costPrice: undefined,
    profitAmount: undefined,
    profitRate: undefined,
    taxRate: undefined,
    taxAmount: undefined,
    warrantyPeriod: undefined,
    isGift: undefined,
    giftMessage: undefined,
    isCustomized: undefined,
    customizationInfo: undefined,
    deliveryDeadline: undefined,
    expectedDeliveryDate: undefined,
    fulfillmentStatus: undefined,
    allocatedWarehouseId: undefined,
    allocatedQuantity: undefined,
    pickedQuantity: undefined,
    shippedQuantity: undefined,
    deliveredQuantity: undefined,
    returnedQuantity: undefined,
    refundedQuantity: undefined,
    cancelReason: undefined,
    remark: undefined,
  }
  formRef.value?.resetFields()
}
</script>